//
//  OAuthViewController.swift
//  sina_yl
//
//  Created by 袁量 on 2017/5/22.
//  Copyright © 2017年 袁量. All rights reserved.
//

import UIKit
import SVProgressHUD
class OAuthViewController: UIViewController {

    @IBOutlet weak var webView: UIWebView!
    override func viewDidLoad() {
        super.viewDidLoad()

        setUpNavigationBarItems()
//        webView.loadRequest(URLRequest(url: URL(string: "http://www.baidu.com")!))
        loadPage()

    }
}

// MARK: - 设置 UI
extension OAuthViewController {
    func setUpNavigationBarItems() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: .plain, target: self
            , action: #selector(OAuthViewController.cancel))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "填充", style: .plain, target: self, action: #selector(OAuthViewController.fillItem))
        title = "登录页面"
    }
}

// MARK: - 响应事件
extension OAuthViewController {
    func cancel() {
        dismiss(animated: true, completion: nil)
    }
    func fillItem() {
        let JSCode = "document.getElementById('userId').value = '18328067022';document.getElementById('passwd').value = 'weibo149'"
        webView.stringByEvaluatingJavaScript(from: JSCode)
    }
    func loadPage() {
        let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(app_key)&redirect_uri=\(redirect_URL)"
        guard let url = NSURL(string: urlStr) else{
            return
        }
        webView.loadRequest(URLRequest(url: url as URL))
    }
}

// MARK: - webView 的代理方法
extension OAuthViewController : UIWebViewDelegate {
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        SVProgressHUD.dismiss()
    }
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        guard let url = request.url else{
            return true
        }
        let urlString = url.absoluteString
        WWLog(mesage: urlString)
        guard urlString.contains("code=") else {
            return true
        }
        let code = urlString.components(separatedBy: "code=").last!
        loadAccessToken(code: code)
        return true
    }
}
extension OAuthViewController {
    func loadAccessToken(code : String) {
        WWLog(mesage: "进入了调用令牌的方法")
         NetworkingTools.shareInstance.loadAccessToken(code) { (result, error) in
            if error != nil{
                return
            }
            guard let accountDict = result else {
                return
            }
            let account = UserAccount(dict: accountDict)
            self.loadUserInfo(account: account)
        }
    }
    private func loadUserInfo(account : UserAccount) {
        guard let accountToken = account.access_token else {
            return
        }
        guard let uid = account.uid else {
            return
        }
        NetworkingTools.shareInstance.loadUserInfo(accountToken, uid: uid) { (result, error) in
            if error != nil {
                return
            }
            guard let userInfoDict = result else {
                return
            }
            account.screen_name = userInfoDict["screen_name"] as? String
            account.avatar_large = userInfoDict["avatar_large"] as? String
            var accountPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
            accountPath = (accountPath as NSString).appendingPathComponent("account.plist")
            NSKeyedArchiver.archiveRootObject(account, toFile: accountPath)
            UserAccountViewModel.shareIntance.account = account
            self.dismiss(animated: true, completion: {
                UIApplication.shared.keyWindow?.rootViewController = WelcomeViewController()
            })
        }
    }
}
